﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.ComponentModel.DataAnnotations;

namespace Uber.WebUI.Models
{
    [PropertiesMustMatch("NewPassword", "ConfirmNewPassword", ErrorMessage = "The password and confirmation password do not match.")]
    public class ResetPasswordInput
    {
        [Required]
        public string NewPassword { get; set; }

        [Required]
        public string ConfirmNewPassword { get; set; }

        [Required(ErrorMessage = "Invalid recovery link")]
        public long Code { get; set; }
        
        [Required(ErrorMessage = "Invalid recovery link")]
        public string Email { get; set; }
    }

    [PropertiesMustMatch("NewPassword", "ConfirmNewPassword", ErrorMessage = "The password and confirmation password do not match.")]
    public class ChangePasswordInput
    {
        [Required]
        public string CurrentPassword { get; set; }

        [Required]
        public string NewPassword { get; set; }

        [Required]
        public string ConfirmNewPassword { get; set; }
    }

    [AttributeUsage(AttributeTargets.Class,
    AllowMultiple = true, Inherited = true)]
    public sealed class PropertiesMustMatchAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage =
            "'{0}' and '{1}' do not match.";
        private readonly object _typeId = new object();

        public PropertiesMustMatchAttribute(string originalProperty,
            string confirmProperty)
            : base(_defaultErrorMessage)
        {
            OriginalProperty = originalProperty;
            ConfirmProperty = confirmProperty;
        }

        public string ConfirmProperty { get; private set; }
        public string OriginalProperty { get; private set; }

        public override object TypeId
        {
            get
            {
                return _typeId;
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                OriginalProperty, ConfirmProperty);
        }

        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties =
               TypeDescriptor.GetProperties(value);
            object originalValue = properties.Find(OriginalProperty,
                true /* ignoreCase */).GetValue(value);
            object confirmValue = properties.Find(ConfirmProperty,
                true /* ignoreCase */).GetValue(value);
            return Object.Equals(originalValue, confirmValue);
        }
    }

}